import { useMutation, useQueryClient } from '@tanstack/react-query';
import { Form, Input, message, Modal } from 'antd';
import dayjs from 'dayjs';
import FileSaver from 'file-saver';
import React from 'react';

import api from '@/apis/api';

import { Logger } from '../useLogger';

interface VerifyPinCodeProps {
  title: string;
  typeName: string;
  visible: boolean;
  setVisible: (visible: boolean) => void;
}

const VerifyPinCode: React.FC<VerifyPinCodeProps> = ({
  title,
  typeName,
  visible,
  setVisible,
}) => {
  const [form] = Form.useForm();

  const queryClient = useQueryClient();

  const DownloadData = useMutation({
    mutationFn: (params: any) => api.ExportLog(params),
    onSuccess: (res: any) => {
      if (res?.success === false) {
        Logger(res?.message);
        message.open({
          type: 'error',
          content: `${res?.message}`,
          key: 'export',
        });
      } else {
        const blob = new Blob([res], { type: 'text/plain;charset=utf-8' });
        const timeStamp = Date.now(); // 直接获取时间戳
        const dd = dayjs(timeStamp).format('YYYY-MM-DD HH:mm:ss');
        // 获取日期时间，格式为：年月日时分秒
        const fileName = `${typeName}-${dd}.csv`; // 文件名包含时间戳
        console.log('fileName', fileName);
        FileSaver.saveAs(blob, fileName);
        message.open({
          type: 'success',
          content: '导出成功',
          key: 'export',
        });
      }
    },
    onError: () => {
      message.open({
        type: 'error',
        content: '导出失败',
        key: 'export',
      });
    },
  });

  // 清空方法
  const ClearLog = useMutation({
    mutationFn: (params: any) => api.ClearLog(params),
    onSuccess: (res: any) => {
      if (res?.success) {
        message.open({
          type: 'success',
          content: '清空成功',
          key: 'clear',
        });
      } else {
        message.error(`清空失败, ${res?.message}`);
      }
    },
    onError: (error) => {
      message.open({
        type: 'error',
        content: '清空失败',
        key: 'clear',
      });
      Logger('清空失败', error);
    },
    onSettled: () =>
      queryClient.invalidateQueries({ queryKey: [`${transformTypeToKey(typeName)}`] }),
    mutationKey: ['clearLog'],
  });

  const transformLogType = (typeName: string) => {
    switch (typeName) {
      case 'manage-log':
        return 0;
      case 'interface-log':
        return 1;
      case 'system-log':
        return 2;
      default:
        return 0;
    }
  };
  const transformTypeToKey = (typeName: string) => {
    switch (typeName) {
      case 'manage-log':
        return 'getManageLog';
      case 'interface-log':
        return 'getInterfaceLog';
      case 'system-log':
        return 'getSystemLog';
      default:
        return 'getSystemLog';
    }
  };
  const handleOk = async () => {
    await form.validateFields();
    const adminPassword: string = form.getFieldValue('adminPassword');
    message.loading({
      content: `${title}中...`,
      key: title === '导出' ? 'export' : 'clear',
    });
    if (title === '导出') {
      DownloadData.mutate({
        log_type: transformLogType(typeName),
        password: adminPassword,
      });
    } else if (title === '清空') {
      ClearLog.mutate({
        log_type: transformLogType(typeName),
        password: adminPassword,
      });
    }
    form.resetFields();
    setVisible(false);
  };
  const handleCancel = () => {
    form.resetFields();
    setVisible(false);
  };

  return (
    <>
      <Modal
        title="验证管理员密码"
        open={visible}
        onOk={handleOk}
        onCancel={handleCancel}
        cancelText="取消"
        okText="确定"
        destroyOnClose
        // okButtonProps={{ disabled: localINFO.getRoleId() !== 1 }}
      >
        <Form
          form={form}
          preserve={false}
          labelCol={{ span: 7 }}
          wrapperCol={{ span: 16 }}
          style={{ maxWidth: 600, marginTop: 24, marginBottom: 24, width: 450 }}
          autoComplete="off"
        >
          <Form.Item
            label="管理员密码"
            name="adminPassword"
            rules={[{ required: true, message: '请输入管理员密码！' }]}
            style={{ marginBottom: 0 }}
          >
            <Input.Password placeholder="请输入管理员密码" autoComplete="new-password" />
          </Form.Item>
        </Form>
      </Modal>
    </>
  );
};

export default VerifyPinCode;
